//
//  NetworkTools.swift
//  weibo
//
//  Created by nick on 15/9/23.
//  Copyright © 2015年 cn.nick. All rights reserved.
//

import UIKit
import AFNetworking
enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    typealias RequestFinishCallBack = (result: AnyObject?, error: NSError?) -> ()
    
    // 网络工具单例
    static let shareInstance: NetworkTools = {
        let instance = NetworkTools(baseURL: nil)
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    // 注册的app信息
    private let appKey = "1516280139"
    private let AppSecret = "58138fa1ca6d9bd71369a7debafef7fc"
    let redirectUrl = "http://www.baidu.com"
    /// -see: [https://api.weibo.com/oauth2/authorize?client_id=1516280139&redirect_uri=http://www.baidu.com](https://api.weibo.com/oauth2/authorize?client_id=1516280139&redirect_uri=http://www.baidu.com)
    // 请求地址
    var OauthUrl: NSURL {
         let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        return NSURL(string: urlString)!
    }
    
    // 请求用户信息
    func loadUserInfo(uid: String, accessToken: String, finished: RequestFinishCallBack) {
        let parameters = ["uid":uid, "access_token":accessToken]
        request(.GET, urlString: "https://api.weibo.com/2/users/show.json", parameters: parameters, finished: finished)
    }
    // 请求token
    func loadAccessToken(code: String, finished: RequestFinishCallBack) {
        
        let parameters = ["client_id":appKey,
        "client_secret":AppSecret,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":redirectUrl]
        request(.POST, urlString: "https://api.weibo.com/oauth2/access_token", parameters: parameters, finished: finished)
    }
    
    // 封装第三方的网络请求
    private func request(method: RequestMethod, urlString: String, parameters: [String: AnyObject]?, finished:RequestFinishCallBack) {
        let success = {
            (task: NSURLSessionDataTask, result: AnyObject) -> () in
            finished(result: result, error: nil)
        }
        let failure = {
            (task: NSURLSessionDataTask, error: NSError) -> () in
            finished(result: nil, error: error)
        }
        if method == RequestMethod.GET {
            GET(urlString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, success: success, failure: failure)
        }
    }
    
    
}
